﻿#ifndef __SS_MALLOC_OBJECT_H__
#define __SS_MALLOC_OBJECT_H__
#include "ssDefaultMalloc.h"
#include "./ssDoublyList.h"
#include "../thread/threadLock/ssAtomicLock.h"

namespace StarSeeker
{

template<typename T>
class ssMallocObj : public ssIMallocObj<T>
{
public:
	ssMallocObj()
	{
	}
	~ssMallocObj()
	{
		Clear();
	}
	//分配对象
	T* Malloc()
	{
		T* tmp = (T*)m_list.Allot();
		if (tmp)
		{
			new (tmp) T();
		}
		return tmp;
	}
	//回收对象
	bool Free(T* pt)
	{
		if (m_list.DataIsFrom(pt))
		{
			pt->~T();
			m_list.Erase(pt);
			return true;
		}
		return false;
	}
	//回收所有分配的对象
	void Recovery()
	{
		typename ssDoublyList<sizeof(T)>::Node_s* itr = m_list.Begin();
		while (itr)
		{
			((T*)itr->Data())->~T();
			itr = itr->Next();
		}
		m_list.Empty();
	}
	//释放没有使用的内存
	void Release()
	{
		m_list.ReleaseFreeNode();
	}
	//内存是否属于池
	bool IsFrom(T* pt)
	{
		return m_list.DataIsFrom(pt);
	}
	//分配的数量
	ulint Count()
	{
		return m_list.UsedCount();
	}
	//释放所有内存
	void Clear()
	{
		typename ssDoublyList<sizeof(T)>::Node_s* itr = m_list.Begin();
		while (itr)
		{
			((T*)itr->Data())->~T();
			itr = itr->Next();
		}
		m_list.Clear();
	}
private:
	ssMallocObj(const ssMallocObj& mc) {}
	void operator= (const ssMallocObj& mc) {}
private:
	ssDoublyList<sizeof(T)>		m_list;
};

template<typename T>
class ssMutexMallocObj : public ssIMallocObj<T>
{
public:
	ssMutexMallocObj()
	{
	}
	~ssMutexMallocObj()
	{
		Clear();
	}
	//分配对象
	T* Malloc()
	{
		T* tmp = 0;
		{
			m_lock.Lock();
			tmp = (T*)m_list.Allot();
			m_lock.Unlock();
			if (tmp)
			{
				new (tmp) T();
			}
		}
		return tmp;
	}
	//回收对象
	bool Free(T* pt)
	{
		if (m_list.DataIsFrom(pt))
		{
			pt->~T();
			m_lock.Lock();
			m_list.Erase(pt);
			m_lock.Unlock();
			return true;
		}
		return false;
	}
	//回收所有分配的对象
	void Recovery()
	{
		m_lock.Lock();
		typename ssDoublyList<sizeof(T)>::Node_s* itr = m_list.Begin();
		while (itr)
		{
			((T*)itr->Data())->~T();
			itr = itr->Next();
		}
		m_list.Empty();
		m_lock.Unlock();
	}
	//释放没有使用的内存
	void Release()
	{
		m_lock.Lock();
		m_list.ReleaseFreeNode();
		m_lock.Unlock();
	}
	//内存是否属于池
	bool IsFrom(T* pt)
	{
		return m_list.DataIsFrom(pt);
	}
	//分配的数量
	ulint Count()
	{
		return m_list.UsedCount();
	}
	//释放所有内存
	void Clear()
	{
		m_lock.Lock();
		typename ssDoublyList<sizeof(T)>::Node_s* itr = m_list.Begin();
		while (itr)
		{
			((T*)itr->Data())->~T();
			itr = itr->Next();
		}
		m_list.Clear();
		m_lock.Unlock();
	}
private:
	ssMutexMallocObj(const ssMutexMallocObj& mc) {}
	void operator= (const ssMutexMallocObj& mc) {}
private:
	ssDoublyList<sizeof(T)>		m_list;
	ssAtomicLock				m_lock;
};

}
#endif
